﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using OI.Async;
using OI.Events;
using OI.Framework;
using OI.DataModel;
using MenuItem = OI.Framework.MenuItem;

namespace OI.ViewModels
{
    [Export(typeof(IShell))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class ShellViewModel : Conductor<IScreen>.Collection.OneActive, 
        IHandle<SelectDataset>, 
        IHandle<ChangeMashupList>,
        IHandle<PopupImage>,
        IHandle<ShowBusy>,
        IHandle<HideBusy>,
        IShell
    {
        #region DATA
        // busy indicator wraps shell and is bound by convention
        public bool IsBusy
        {
            get { return _IsBusy; }
            private set
            {
                _IsBusy = value;
                NotifyOfPropertyChange(() => IsBusy);
            }
        }
        private bool _IsBusy;

        // busy content
        public string BusyContent
        {
            get { return _BusyContent; }
            private set
            {
                _BusyContent = value;
                NotifyOfPropertyChange(() => BusyContent);
            }
        }
        private string _BusyContent = "please wait...";


        // main menu
        // the menu items for selecting the type of view
        public BindableCollection<MenuItem> MainMenu
        {
            get
            {
                if (_MainMenu == null)
                {
                    _MainMenu = new BindableCollection<MenuItem>
                    {
                        new MenuItem
                        {
                            Header = "catalog", Width = 130, IsEnabled = true, IsSelected = true
                        },
                        new MenuItem
                        {
                            Header = "map", Width = 90, IsEnabled = false, IsSelected = false
                        },
                        new MenuItem
                        {
                            Header = "apps", Width = 80, IsEnabled = true, IsSelected = false
                        }
                    };
                }
                return _MainMenu;
            }
        }
        private BindableCollection<MenuItem> _MainMenu;
        public MenuItem CurrentMenuItem { get; private set; }


        // top right screen area conducts multiple views
        [Import]
        public TopRightViewModel TopRight { get; set; }


        // collection of IScreen activations for back button usage
        public Stack<Tuple<IScreen, MenuItem>> ScreenStack = new Stack<Tuple<IScreen, MenuItem>>();
        public bool CanGoBack { get { return (ScreenStack.Count > 0); } }

        // customer title block
        public string CustomerTitleBlock { get { return Configuration.Jurisdiction.TitleBlock; } }

        // used to manage pop-back to previous display state
        public bool PopBackInProgress { get; set; }

        // uri to customer logo
        public string LogoUri
        {
            get
            {
                return Configuration.Jurisdiction.CustomerImageURI;
            }
        }

        private readonly IEventAggregator Events;
        private readonly IWindowManager WindowManager;

        #endregion


        [ImportingConstructor]
        public ShellViewModel(IEventAggregator events, IWindowManager wm)
        {
            Events = events;
            events.Subscribe(this);
            WindowManager = wm;
        }


        // begin asyn-loading process
        protected override void OnInitialize()
        {
            base.OnInitialize();

            // set configuration with init params
            Configuration.ConnectionString = App.InitParams["OIConnectionString"];
            Configuration.BingServiceKey = App.InitParams["BingServiceKey"];

            Coroutine.BeginExecute(Setup()); 
        }


        // setup application
        public IEnumerator<IResult> Setup()
        {
            // load the jurisdiction by the readable string passed in via querystring
            string jurisID = Configuration.GetQueryStringJurisdictionID();
            Busy(true, "loading jurisdiction: " + jurisID + "...");

            var jq = new CatalogQuery<OIJurisdiction>(jurisID);
            yield return jq;

            // if we couldn't find a jurisdiction
            if (jq.Results == null || jq.Results.Count == 0)
            {
                HandleException(new Exception("Failed to find jurisdiction: " + jurisID), "Setup error:");
            }
            else
            {
                // save in static instance
                Configuration.Jurisdiction = jq.Results[0];

                // now that the jurisdiction loaded, notify ui updates
                NotifyOfPropertyChange(() => CustomerTitleBlock);
                NotifyOfPropertyChange(() => LogoUri);

                // async load mashup map definition
                Busy(true, "loading mashup...");
                var mdq = new MDNMapDefinitionQuery(Configuration.Jurisdiction.MashupMapID);
                yield return mdq;

                // save the global mashup map def
                var mmd = IoC.Get<MashupMapDefinition>();
                mmd.SerialMap = mdq.MapDefinitionString;
                mmd.Map = mdq.MapDefintion;

                Busy(false);

                // start at the catalog, we must load datasets now
                ChildActivate(IoC.Get<CatalogViewModel>());
                CurrentMenuItem = MainMenu[0];

                // if we have a share id on the querystring, launch mashup
                string shareID = Configuration.GetQueryStringShareID();
                if (!string.IsNullOrEmpty(shareID))
                {
                    // new these up so it can receive sharing events
                    // it will get bound to its view later
                    IoC.Get<MashupMapViewModel>();

                    var id = new Guid(shareID);
                    Events.Publish(new RestoreStateRequest
                    {
                        ID = id
                    });
                }

                // if we have a filter on querystring, publish it to be appended to mashup
                string filterLayerID = Configuration.GetQueryStringFilterLayerID();
                if (!string.IsNullOrEmpty(filterLayerID))
                {
                    string filterMetadata = Configuration.GetQueryStringFilterMetadata();
                    if (!string.IsNullOrEmpty(filterMetadata))
                    {
                        var items = FilterItem.ParseFilterItems(filterMetadata);
                        if (items.Count == 1)
                        {
                            Events.Publish(new AppendLayerFilter
                            {
                                LayerID = filterLayerID,
                                Item = items[0]
                            });
                        }
                    }
                }
            }
        }

        [Import]
        public MessageBoxViewModel MessageBox
        {
            get;
            set;
        }

        // top-level point where exceptions get routed
        public void HandleException(Exception ex, string title)
        {
            if (Configuration.GetDebug())
            {
                MessageBox.DisplayName = "Error";

                MessageBox.Message = (ex != null ? title.Trim().TrimEnd(':') + ": " + ex.Message : title);

                Busy(false);
            }
        }


        // selects a particular child view for the primary content area
        // also manages back queue and top-right content
        private void ChildActivate(IScreen childView)
        {
            // save current screen to back-stack?
            if (ActiveItem != null &&
                childView != ActiveItem &&
                !PopBackInProgress)
            {
                var item = new Tuple<IScreen, MenuItem>(ActiveItem, CurrentMenuItem);
                ScreenStack.Push(item);
            }

            if (childView is CatalogViewModel)
            {
                TopRight.LoadSearchPanel(false);
            }
            else if (childView is MashupViewModel)
            {
                TopRight.LoadSearchPanel(true);
            }
            else if (childView is DatasetDetailsViewModel)
            {
                TopRight.LoadDatasetDetailsOptionsPanel();
            }
            else if (childView is AppsViewModel)
            {
                TopRight.Close();
            }
            

            // activate new screen
            ActivateItem(childView);
            NotifyOfPropertyChange(() => CanGoBack);
        }


        // called when menu selection is made
        public void MenuSelect(MenuItem item)
        {
            if (!PopBackInProgress)
            {
                if (item.Header == "catalog")
                {
                    ChildActivate(IoC.Get<CatalogViewModel>());
                }
                else if (item.Header == "map")
                {
                    ChildActivate(IoC.Get<MashupViewModel>());
                }
                else if (item.Header == "apps")
                {
                    ChildActivate(IoC.Get<AppsViewModel>());
                }
            }
            CurrentMenuItem = item;
        }


        // handle a dataset selection from the catalog
        public void Handle(SelectDataset message)
        {
            var ds = message.DataSet;

            if (ds.IsPublished)
            {
                var vm = new DatasetDetailsViewModel(ds);
                ChildActivate(vm);
            }
        }


        // handle a mashup list change - show/hide mashup menu item
        public void Handle(ChangeMashupList message)
        {
            // show the mashup link if we have layers in the mashup
            bool enable = message.MashupList.Count > 0;
            MainMenu.Apply((x) => { if (x.Header == "map") x.IsEnabled = enable; });

            // if we added an item, go directly to the mashup screen
            if (message.Added)
            {
                ChildActivate(IoC.Get<MashupViewModel>());
                MainMenu.Apply((x) => x.IsSelected = (x.Header == "map"));
            }
        }


        // handle a request to pop an image up in a dialog
        public void Handle(PopupImage message)
        {
            var ip = new ImagePopupViewModel(message.Image, message.ImageUri);
            WindowManager.ShowDialog(ip);
        }


        // go-back through screen queue
        public void GoBack()
        {
            if (ScreenStack.Count > 0)
            {
                PopBackInProgress = true;
                var history = ScreenStack.Pop();

                // select correct menu item
                var mi = history.Item2;
                MainMenu.Apply((x)=> x.IsSelected = (x == mi));

                // activate correct child view
                ChildActivate(history.Item1);
                PopBackInProgress = false;
            }
        }


        // busy indicator methods
        public void Busy(bool enable)
        {
            Busy(enable, "please wait...");
        }
        public void Busy(bool enable, string caption)
        {
            BusyContent = caption;
            IsBusy = enable;
        }

        public void Handle(ShowBusy message)
        {
            Busy(true, message.Caption);
        }

        public void Handle(HideBusy message)
        {
            Busy(false);
        }
    }
}
